'use strict';
const { Service } = require('egg');
class RegisterService extends Service {
  async checkUsername(query,control){
    const {ctx,app} = this;
    if(query){
      let res = control.checkInput({form:query,bean:"user"});
      if(res.code===0){
        return res;
      }
      const keyword = {};
      if(query.username){
        keyword.key = "username";
        keyword.value = "用户名";
        keyword.paramValue = query.username
      }else if(query.name){
        keyword.key = "name";
        keyword.value = "昵称";
        keyword.paramValue = query.name;
      }else{
        return {code:0,msg:"请输入正确的格式"};
      }
      let result;
      if(query.username && query.name){
        result = await app.model.User.findOne({
          where: {
            [app.Sequelize.Op.or]: [
              { username: query.username },
              { name: query.name }
            ]
          }
        });
      }else{
        result = await app.model.User.findOne({where:{[keyword.key]:keyword.paramValue}});
      }
      if(result){
        if(result.username == query.username){
          keyword.value = "用户名"
        }else{
          keyword.value = "昵称"
        }
        let msg = "该"+keyword.value+"已被使用！";
        query.body = {code:0,msg}
      }else{
        query.body = {code:1,msg:`恭喜该${keyword.value}可以使用`}
      }
      return query.body;
    }
  }
}

module.exports = RegisterService;
